/**
 * 视图运行- 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0000.FormView.Runtime.MainForm", {
  extend: "PSI.AFX.Form.MainForm",
  border: 0,

  config: {
    fid: null
  },

  initComponent() {
    const me = this;

    PCL.apply(me, {
      tbar: {
        id: "PSI_FormView_RuntimeMainForm_toolBar",
        xtype: "toolbar"
      },
      layout: "fit",
      border: 0,
      items: [{
        id: "PSI_FormView_RuntimeMainForm_mainPanel",
        layout: "border",
        items: []
      }]
    });

    me.callParent(arguments);

    me._toolBar = PCL.getCmp("PSI_FormView_RuntimeMainForm_toolBar");

    me._mainPanel = PCL.getCmp("PSI_FormView_RuntimeMainForm_mainPanel");

    me.fetchMeatData();
  },

  getMetaData() {
    return this._md;
  },

  fetchMeatData() {
    const me = this;
    const el = me.getEl();
    el && el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0000/FormView/fetchMetaDataForRuntime"),
      params: {
        fid: me.getFid()
      },
      callback(options, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);

          me._md = data;

          me.initUI();
        }

        el && el.unmask();
      }
    });
  },

  initUI() {
    const me = this;

    const md = me.getMetaData();
    if (!md) {
      return;
    }

    // 按钮
    const toolBar = me._toolBar;

    toolBar.add(["-", {
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      iconCls: "PSI-tb-close",
      handler() {
        me.closeWindow();
      }
    }]);

    const mainPanel = me._mainPanel;
    if (md.layoutType == "2") {
      // 左右布局
      for (let i = 0; i < md.subView.length; i++) {
        const sv = md.subView[i];
        const wh = sv.widthOrHeight;
        if (!wh.endsWith("%")) {
          wh = parseInt(wh);
          if (wh < 50) {
            wh = 50;
          }
        }
        const item = {
          border: 0,
          layout: "fit",
          region: sv.region,
          width: wh,
          items: [{
            xtype: sv.xtype
          }]
        };
        if (sv.region == "west") {
          PCL.apply(item, {
            split: true
          });
        }

        mainPanel.add(item);
      }
    } else if (md.layoutType == "3") {
      // 上下布局
      for (let i = 0; i < md.subView.length; i++) {
        const sv = md.subView[i];
        const wh = sv.widthOrHeight;
        if (!wh.endsWith("%")) {
          wh = parseInt(wh);
          if (wh < 50) {
            wh = 50;
          }
        }
        const item = {
          border: 0,
          layout: "fit",
          region: sv.region,
          height: wh,
          items: [{
            xtype: sv.xtype
          }]
        };
        if (sv.region == "south") {
          PCL.apply(item, {
            split: true
          });
        }

        mainPanel.add(item);
      }
    }
  }
});
